<?php

/**
 * 作者：云喵软件开发工作室
 * 官网：https://www.meoyun.com
 */

namespace app\api\controller;

use app\model\MediaCheckModel;
use app\model\PostModel;
use app\model\FavoritesModel;
use app\model\LikesModel;
use app\model\MessageModel;
use app\model\UsersModel;
use app\service\FileService;
use app\service\MessageService;
use app\service\WeChatMnpService;
use Respect\Validation\Exceptions\ValidationException;
use Respect\Validation\Validator as v;
use support\Request;
use support\Response;

class Post extends BaseApi
{
    protected $dataModel = PostModel::class;
    protected array $with  = ['user'];
    protected array $allowSearch = ['category_id','user_id','discuss_id'];

    //发布帖子
    public function publish(Request $request): Response
    {
        $userId = $this->getUserId();

        $user = UsersModel::checkUser($userId);

        try {
            $params = v::input($request->all(), [
                'title' => v::nullable(v::stringType())->length(0,20)->setName("标题"),
                'category_id' => v::nullable(v::stringType())->setName('类目'),
                'discuss_id' => v::nullable(v::stringType())->setName('话题'),
                'content' => v::notEmpty()->setName('内容'),
                'media' => v::arrayType()->setName("媒体")
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        (new WeChatMnpService())->msgSecCheck($user["openid"],$params["content"]);

        $params["user_id"] = $userId;

        $post = PostModel::create($params);

        return $this->success($post);
    }

    //获取当前用户收藏的帖子列表
    public function favorites(Request $request): Response
    {
        $userId = $this->getUserId();

        $list = FavoritesModel::where('user_id', $userId)->orderBy('created_at', 'desc')->with(["post"])->paginate(self::DEFAULT_PAGE_SIZE);

        return $this->dataByPage($list);
    }

    //获取当前用户点赞的帖子列表
    public function likes(Request $request): Response
    {
        $userId = $this->getUserId();

        $list = LikesModel::where('user_id', $userId)->orderBy('created_at', 'desc')->with(["post"])->paginate(self::DEFAULT_PAGE_SIZE);

        return $this->dataByPage($list);
    }

    //获取当前用户发布的帖子列表
    public function currentUser(Request $request): Response
    {
        $userId = $this->getUserId();

        // 查询用户收藏的帖子ID
        $list = PostModel::where('user_id', $userId)->orderBy('created_at', 'desc')->with("user")->paginate(self::DEFAULT_PAGE_SIZE);

        return $this->dataByPage($list);
    }

    //通过用户ID获取用户收藏的帖子列表
    public function favoritesByUserId(Request $request): Response
    {
        try {
            $params = v::input($request->get(), [
                'user_id' => v::notEmpty()->setName('用户ID')
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        $userId = $params['user_id'];

        $list = FavoritesModel::where('user_id', $userId)->orderBy('created_at', 'desc')->with(["post"])->paginate(self::DEFAULT_PAGE_SIZE);

        return $this->dataByPage($list);
    }

    //通过用户ID获取用户点赞的帖子列表
    public function likesByUserId(Request $request): Response
    {
        try {
            $params = v::input($request->get(), [
                'user_id' => v::notEmpty()->setName('用户ID')
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        $userId = $params['user_id'];

        $list = LikesModel::where('user_id', $userId)->orderBy('created_at', 'desc')->with(["post"])->paginate(self::DEFAULT_PAGE_SIZE);

        return $this->dataByPage($list);
    }

    //点赞帖子
    public function like(Request $request): Response
    {
        try {
            $params = v::input($request->all(), [
                'post_id' => v::stringType()->notEmpty()->setName("帖子ID")
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        $userId = $this->getUserId();
        $postId = $params['post_id'];

        // 检查帖子是否存在
        $post = PostModel::find($postId);
        if (!$post) {
            return $this->fail('帖子不存在');
        }

        // 检查是否已经点赞
        $existingLike = LikesModel::where('user_id', $userId)->where('post_id', $postId)->first();

        if ($existingLike) {
            // 如果已经点赞，则取消点赞
            $existingLike->delete();
            // 减少帖子的点赞数
            $post->decrement('like_count');
            return $this->success(['is_liked' => false], '取消点赞成功');
        } else {
            // 如果没有点赞，则添加点赞
            LikesModel::create([
                'user_id' => $userId,
                'post_id' => $postId
            ]);
            // 增加帖子的点赞数
            $post->increment('like_count');

            // 发送点赞消息给帖子作者
            MessageService::sendMessage(
                $userId,
                $post->user_id,
                '赞了你的帖子',
                MessageModel::TYPE_LIKE,
                $postId
            );

            return $this->success(['is_liked' => true], '点赞成功');
        }
    }

    //收藏帖子
    public function favorite(Request $request): Response
    {
        try {
            $params = v::input($request->all(), [
                'post_id' => v::stringType()->notEmpty()->setName("帖子ID")
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        $userId = $this->getUserId();
        $postId = $params['post_id'];

        // 检查帖子是否存在
        $post = PostModel::find($postId);
        if (!$post) {
            return $this->fail('帖子不存在');
        }

        // 检查是否已经收藏
        $existingFavorite = FavoritesModel::where('user_id', $userId)->where('post_id', $postId)->first();

        if ($existingFavorite) {
            // 如果已经收藏，则取消收藏
            $existingFavorite->delete();
            // 减少帖子的收藏数
            $post->decrement('favorite_count');
            return $this->success(['is_favorited' => false], '取消收藏成功');
        } else {
            // 如果没有收藏，则添加收藏
            FavoritesModel::create([
                'user_id' => $userId,
                'post_id' => $postId
            ]);
            // 增加帖子的收藏数
            $post->increment('favorite_count');

            // 发送收藏消息给帖子作者
            MessageService::sendMessage(
                $userId,
                $post->user_id,
                '收藏了你的帖子',
                MessageModel::TYPE_FAVORITE,
                $postId
            );

            return $this->success(['is_favorited' => true], '收藏成功');
        }
    }

    //获取帖子详情
    public function getInfo(Request $request): Response
    {
        try {
            $params = v::input($request->all(), [
                'id' => v::stringType()->notEmpty()->setName("ID")
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        try {
            $userId = $this->getUserId(false);
            $postId = $params["id"];

            // 获取帖子基本信息
            $query = $this->buildBaseQuery();
            $post = $query->where('id', $postId)->firstOrFail();

            // 如果用户已登录，检查当前用户是否点赞和收藏了这个帖子
            if ($userId) {
                $isLiked = LikesModel::where('user_id', $userId)->where('post_id', $postId)->exists();
                $isFavorited = FavoritesModel::where('user_id', $userId)->where('post_id', $postId)->exists();

                $post->is_liked = $isLiked;
                $post->is_favorited = $isFavorited;
            } else {
                // 未登录用户默认为未点赞和未收藏
                $post->is_liked = false;
                $post->is_favorited = false;
            }

            $post->increment('view_count'); //浏览量自增

            return $this->success($post);
        } catch (\Exception $e) {
            return $this->fail("获取数据失败: {$e->getMessage()}", 400);
        }
    }

    public function wechatCheckImg(Request $request)
    {
        try {
            $params = v::input($request->all(), [
                'post_id' => v::notEmpty()->setName("ID")
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        $userId = $this->getUserId();
        $user = UsersModel::where("id", $userId)->first();

        $imgList = PostModel::where("id", $params["post_id"])->value("media");

        foreach ($imgList as $imgSrc) {
            $imgSrc = FileService::getFileUrl($imgSrc);
            $checkInfoJSon = (new WeChatMnpService())->mediaCheckAsync($user["openid"], $imgSrc);
            $checkInfo = json_decode($checkInfoJSon);
            MediaCheckModel::create([
                'trace_id' => $checkInfo->trace_id,
                'post_id' => $params["post_id"],
                'media_src' => $imgSrc
            ]);
        }

        return $this->success();
    }

}
